package com.ocm.tourism.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.ocm.tourism.core.domain.Advertisement;
import com.ocm.tourism.core.domain.Business;
import com.ocm.tourism.core.domain.BusinessType;
import com.ocm.tourism.core.domain.Priority;
import com.ocm.tourism.core.model.BusinessCriteria;
import com.ocm.tourism.core.service.BusinessService;
import com.ocm.tourism.core.service.CommonItemsService;

@RequestMapping("/businesses")
@Controller
public class BusinessController {

	@Autowired
    BusinessService businessService;

	@Autowired
    CommonItemsService commonItemsService;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Business business, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, business);
            return "businesses/create";
        }
        uiModel.asMap().clear();
        businessService.saveBusiness(business);
        return "redirect:/businesses/" + encodeUrlPathSegment(business.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value="/create/light",method=RequestMethod.GET)
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Business());
        return "businesses/create/light";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("business", businessService.findBusiness(id));
        uiModel.addAttribute("itemId", id);
        return "businesses/show";
    }

	@RequestMapping(value = "/management", method = RequestMethod.GET)
   public String list(Model uiModel) {
      uiModel.addAttribute("businesses", new ArrayList<BusinessService>());
      uiModel.addAttribute("businessCriteria", new BusinessCriteria());
      return "businesses/management";
   }

	@RequestMapping(value = "/management/{id}", method = RequestMethod.GET)
   public String viewDetail(@PathVariable("id")Long businessId, Model uiModel) {
      Business business = this.businessService.findBusiness(businessId);
      String returnStr = "businesses/management";
      switch (business.getBusinessType()){
         case HOTEL:
            returnStr = "forward:/hotel/detail/" + businessId; 
            break;
         case COFFEE:
            returnStr = "forward:/coffee/"+ businessId+"/detail"; 
            break;
         case FOODSTALL:
            returnStr = "forward:/foodstall/"+ businessId+"/detail"; 
            break;
         case RESTAURANT:
            returnStr = "forward:/restaurant/" + businessId +"/detail"; 
            break;
         case TOURISTAGENCY:
            returnStr = "forward:/touristAgency/detail/" + businessId; 
            break;
      }
      
      return returnStr;
   }

	@RequestMapping(value = "/management/search/advantage", method = RequestMethod.POST)
   public String search(BusinessCriteria businessCriteria, Model uiModel) {
      uiModel.addAttribute("businesses", this.businessService.findBusinesses(businessCriteria.fill(), 0, 50));
      uiModel.addAttribute("businessCriteria", businessCriteria);
      return "businesses/management";
   }

   @RequestMapping(value = "/management/{id}/advs", method = RequestMethod.GET)
   public String advertisement(@PathVariable("id")Long businessId, Model uiModel) {
      Business business = this.businessService.findBusiness(businessId);
      uiModel.addAttribute("business", business);
      uiModel.addAttribute("businessId", businessId);
      uiModel.addAttribute("prioritise", Arrays.asList(Priority.values()));
      uiModel.addAttribute("advertisement", business.getAdvertisement() == null ? new Advertisement() : business.getAdvertisement());
      return "businesses/adv";
   }
	
   @RequestMapping(value = "/management/{id}/advs", method = RequestMethod.PUT)
   public String advertisement(@PathVariable("id")Long businessId,@Valid Advertisement advertisement, Model uiModel) {
      Business business = this.businessService.findBusiness(businessId);
      Advertisement actualAdvertisement = business.getAdvertisement();
      if (actualAdvertisement != null){
         actualAdvertisement.setActived(advertisement.getActived());
         actualAdvertisement.setContent(null);
         actualAdvertisement.setEndDate(advertisement.getEndDate());
         actualAdvertisement.setForever(advertisement.getForever());
         actualAdvertisement.setModifiedDate(new Date(System.currentTimeMillis()));
         actualAdvertisement.setPriority(advertisement.getPriority());
         actualAdvertisement.setStartDate(advertisement.getStartDate());
         actualAdvertisement.setTitle(null);
         actualAdvertisement.setVersion(advertisement.getVersion());
         business.setAdvertisement(actualAdvertisement);
      }else {
         business.setAdvertisement(advertisement);
      }
      this.businessService.saveBusiness(business);
      return "redirect:/businesses/management";
   }

	void populateEditForm(Model uiModel, Business business) {
        uiModel.addAttribute("business", business);
        uiModel.addAttribute("countrys", commonItemsService.findAllCountrys());
        uiModel.addAttribute("bussinessTypes", Arrays.asList(BusinessType.values()));
        uiModel.addAttribute("commonitemses", commonItemsService.findAllCommonItemses());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
